import logging
import random
import re
from django.contrib import auth

from django.contrib.auth import login, logout
from django.http.response import HttpResponse
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView
from apps.users.models import User
from utils.captcha.captcha import captcha



# Create your views here.


# 这是实现图片验证码
class ImageView(APIView):
    def get(self, request):
        # 获取前端传来的参数
        cur = request.GET.get('cur')
        # 获取第三包，并生成图片内容和图片
        image_code, image = captcha.generate_captcha()
        # 并存入redis中
        redis_client = get_redis_connection('code')
        redis_client.setex(cur, 300, image_code)
        # 转换为image格式给前端
        return HttpResponse(image, content_type='image/jpeg')


# 这是发送验证码
class SendMessageView(APIView):
    def post(self, request):
        # 获取前端传来的参数
        image_code_id = request.data.get('id')
        image_code = request.data.get('text')
        mobile = request.data.get('mobile')
        # 判断是否缺少参数
        if not all([image_code_id, image_code, mobile]):
            return Response({'errno': 400, 'errmsg': '缺少参数'})
        # 进行手机号的判断
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return Response({'errno': 400, 'errmsg': '参数mobile有误'})
        # 从redis中拿到我们的图片验证码id
        a2 = get_redis_connection('code').get(image_code_id)
        # 进行判断是否存在图片验证码
        if a2 is None:
            return Response({'errno': 400, 'errmsg': '图片验证码过期'})
        # 进行比对，输入的图片验证码是否跟redis中存储的是否一样
        # if a2.decode('utf8').lower() != image_code.lower():
        #     return Response({'errmsg': '图片验证码错误'}, status=400)
        # 随机生成一个短信验证码
        code = str(random.randint(1000, 9999))
        # 进行一个django管理日志
        loger = logging.getLogger('django')
        # 将验证码输出在控制台上
        loger.info(code)
        bb = get_redis_connection()
        from celery_tasks.sms.tasks import sms_code
        sms_code(mobile,code)
        # 将验证码存入redis当中   并设置上过期时间
        bb.set(mobile, code, 600)
        return Response({"errno": "0", "errmsg": "发送成功",'smscode':code})


class RegisterView(APIView):
    def post(self, request):
        # 接受参数
        mobile = request.data.get('mobile')
        phonecode = request.data.get('phonecode')
        password = request.data.get('password')
        if not all((mobile, password, phonecode)):
            return Response({'errno': 400, 'errmsg': '缺少参数'})
        # 判断密码是否符合规范
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return Response({'errno': 400, 'errmsg': 'password格式有误!'})
        # 判断手机号是否规范
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return Response({'errno': 400, 'errmsg': 'mobile格式有误!'})
        # 进行获取验证码
        a2 = get_redis_connection().get(mobile)
        if a2 is None:
            return Response({'errno': 400, 'errmsg': '验证码错误'})
        if a2.decode() != phonecode:
            return Response({'errno': 400, 'errmsg': '手机验证码错误'})
        # 进行保存并对密码进行加密
        try:
            User.objects.create_user(
                username=mobile,
                mobile=mobile,
                password=password
            )
        except:
            return Response({'errno': 400, 'errmsg': '注册失败'})
        return Response({'errno': 0, 'errmsg': 'ok'})


class LoginView(APIView):
    def post(self, request):
        # 接受参数
        mobile = request.data.get('mobile')
        password = request.data.get('password')
        if not all((mobile, password)):
            return Response({'errno': 0, 'errmsg': '缺少参数'})
        # 进行对加密过的密码进行解密
        try:
            user = User.objects.get(mobile=mobile)
            if not user.check_password(password):
                return Response({'errno':400,'errmsg':'登录失败'})
        except:
            return Response({'errno':400,'errmsg':'没有该账号'})
        # 进行状态保持
        login(request, user)
        # request.session.set_expiry(None)
        # 进行设置cookie
        a1 = Response({'errno': 0, 'errmsg': 'ok'})
        a1.set_cookie('name', user.mobile)
        return a1

    def get(self, request):
        # 获取用户信息
        user = request.user
        # 进行判断用户是否登录
        if not user.is_authenticated:
            return Response({'errno': 0, 'errmsg': '用户未登录'})
        else:
            return Response(
                {
                    "errno": "0",
                    "errmsg": "已登录",
                    "data": {
                        "name": request.user.username,
                        'user_id': request.user.id
                    }
                })

    def delete(self, request):
        # 进行退出登录，
        logout(request)
        a1 = Response({
            "errno": "0",
            "errmsg": "已登出"
        })
        # 并把登录时的cookie删除
        a1.delete_cookie('name')
        return a1
